<?php
/**
 * Created by PhpStorm.
 * User: justin
 * Date: 2019/1/23
 * Time: 10:08
 */


declare(strict_types=1);

namespace App\Library\Task\library\queue;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Library\Log\Log;
use App\Library\Task\library\queue\drivers\mns\QueueClientMns;
use App\Library\Task\library\queue\drivers\redis\QueueClientRedis;
use Hyperf\Utils\ApplicationContext;

class QueueClient
{
    public static function _getQueueObject() {

        $queueDriver = config('goods.task_drivers_default.queue_driver');

        //如果想使用使用Mns等，可以加case
        switch ($queueDriver){
            case  'redis':
                Log::info(new BusinessException(ErrorCode::TASK_RECORD, 'QueueClient 队列选择：QueueClientRedis'));
                return ApplicationContext::getContainer()->get(QueueClientRedis::class);
            case 'mns':
                Log::info(new BusinessException(ErrorCode::TASK_RECORD, 'QueueClient 队列选择：QueueClientMns'));
                return ApplicationContext::getContainer()->get(QueueClientMns::class);
            default:
                return ApplicationContext::getContainer()->get(QueueClientRedis::class);
        }
    }

    /**
     * Notes:入列
     * @param $key
     * @param $value
     * @param string $queueDriverGroupName  队列组名
     * @return mixed
     * @throws \Exception
     */
    public static function push($key, $value, $queueDriverGroupName = '') {
        $client = self::_getQueueObject();
        $queueDriverGroup = self::getQueuesByGroupName($queueDriverGroupName);
        $queueDriver = self::randOneQueue($queueDriverGroup);
        Log::info(new BusinessException(ErrorCode::TASK_RECORD, 'QueueClient 入列名称：'.$queueDriver));
        return $client->push($key, $value, $queueDriver);
    }

    /**
     * Notes:根据组名获取队列
     * @param $group_name
     * @return array
     *
     * 找不到组名则返回当前组
     */
    public static function getQueuesByGroupName($group_name = '')
    {
        $queueGroupList = [];
        $queueList      = config('goods.task_drivers_default.queue_list');
        foreach ($queueList as $queueName => $value) {
            if ($value['belong_group'] == $group_name) {
                $queueGroupList[] = $queueName;
            }
        }
        return $queueGroupList ?: [$group_name];
    }

    /**
     * Notes:随机获取一个队列
     * @param array $queueList
     * @return mixed|string
     * @throws \Exception
     */
    public static function randOneQueue($queueList=[]){
        //随机取一个
        if(!empty($queueList)){
            $queueDriver = $queueList[array_rand($queueList,1)]? : array_pop($queueList);
            if(empty($queueDriver)){
                throw new \Exception('队列名格式不规范，取不到队列');
            }
        }else{
            $queueDriver = '';
        }
        return $queueDriver;
    }
}